<script lang="ts" setup>
  import { FileTextOutlined } from '@ant-design/icons-vue'
  import { message } from 'ant-design-vue'
  import axios from 'axios'
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { approveDataProduct, changeStatusDataProduct, getDataProductActionRecord, getDataProductById, getResourceApproveList, saveDataProduct } from '/@/api/exchange/dataProduct'
  import { previewFile, previewStructuredFile } from '/@/api/exchange/requirement'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'
  import { formatDate } from '/@/utils/date'

  const token = getToken() || ''
  const platformCode = import.meta.env.VITE_GLOB_PLATFORMCODE
  const router = useRouter()
  const route = useRoute()
  const { id } = route.query
  const dataProductDetail = ref<DataProductTypes.DetailIResponse>()
  const actionRecordList = ref<DataProductTypes.ActionRecordIResponse[]>([])
  const auditRecordList = ref<DataProductTypes.AuditRecordIResponse[]>([])
  const statusObj = reactive({ 1: '已保存', 2: '待审核', 3: '已上架', 4: '已下架' })
  const priceObj = reactive({ 1: '一口价', 2: '单价', 3: '面议' })
  // 预览非结构化数据
  const fileId = ref<string>()
  const previewLoading = ref(false)
  const previewVisible = ref(false)
  const previewImage = ref<string>()
  // 审核
  const actionTab = ref(1)
  const auditValue = ref<number>()
  const auditIdea = ref<string>()
  // 文件数据
  const listObj = ref<any>()
  const structuredList = ref<DataProductTypes.fileType[]>([])
  const structuredFileList = ref<any[]>([])
  const unstructuredList = ref<DataProductTypes.fileType[]>([])
  // 下架
  const visible = ref(false)
  const operationDesc = ref<string>()

  /**
   * 路由跳转：数据详情页
   * @param record 产品数据
   */
  const goDataDetail = () => {
    router.push({
      path: '/data-product/data-detail',
      query: { fileString: JSON.stringify(structuredFileList.value) },
    })
  }

  // 批量下载
  const batchDownload = async () => {
    const fileList = [...structuredList.value, ...unstructuredList.value]
    const fileIds = fileList.map((item) => item.fileId)
    const fileUrl = `${import.meta.env.VITE_BASE_API_PATH}/zeus/standard/dc-file/batchFileDownload`
    const formData = new FormData()
    formData.append('ids', fileIds.join(','))
    formData.append('platformCode', platformCode)
    try {
      // 发送 POST 请求
      const response = await axios.post(fileUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token,
        },
        responseType: 'blob', // 指定响应类型为二进制数据
      })

      // 处理响应
      if (response.status === 200) {
        // 创建一个临时链接
        const url = window.URL.createObjectURL(new Blob([response.data]))
        // 创建一个隐藏的 <a> 标签
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'files.zip') // 设置下载文件的名称
        document.body.appendChild(link)
        link.click() // 触发下载
        document.body.removeChild(link) // 移除 <a> 标签
        window.URL.revokeObjectURL(url) // 释放临时链接
      } else {
        throw new Error('下载失败')
      }
    } catch (error) {
      console.error('下载出错:', error)
      message.error('下载失败，请重试')
    }
  }

  // 非结构化数据预览
  const unstructuredPreviewFile = async (id: string) => {
    fileId.value = id
    const fileUrl = `${import.meta.env.VITE_BASE_API_PATH}/zeus/standard/dc-file/unstructuredPreviewDownload`
    const formData = new FormData()
    formData.append('id', id)
    formData.append('platformCode', platformCode)
    previewLoading.value = true
    try {
      // 发送 POST 请求
      const response = await axios.post(fileUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token,
        },
        responseType: 'blob', // 指定响应类型为二进制数据
      })
      // 处理响应
      if (response.status === 200) {
        const blob = new Blob([response.data], { type: response.headers['content-type'] })
        const url = window.URL.createObjectURL(blob)
        if (url) {
          previewImage.value = url
          previewVisible.value = true
        } else {
          message.error('预览失败，请重试')
        }
        previewLoading.value = false
      } else {
        throw new Error('预览失败')
        previewLoading.value = false
      }
    } catch (error) {
      previewLoading.value = false
      console.error('预览出错:', error)
      message.error('预览失败，请重试')
    }
  }

  // 关闭预览
  const handleCancel = () => {
    previewVisible.value = false
    previewImage.value = ''
  }

  // 结构化数据预览
  const structuredPreviewFile = async (id) => {
    const { responseCode, responseData } = await previewStructuredFile({
      id: id,
      sheetNo: 0,
      headerRowNumber: 1,
      previewRows: 10,
    })
    if (responseCode === 100000000) {
      listObj.value = responseData.data
    }
  }

  // 审核
  const approveRequire = async () => {
    if (!auditValue.value) {
      message.error('请选择审核状态')
      return
    }
    if (!auditIdea.value) {
      message.error('请输入审核意见')
      return
    }
    const params = {
      resourceId: id,
      approveStatus: auditValue.value,
      approveMsg: auditIdea.value,
    }
    const { responseCode } = await approveDataProduct(params)
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('操作成功')
      pageBack()
    }
  }

  // 提交申请
  const onSaveDataProduct = async () => {
    const params = {
      status: 2,
      id: id,
    }
    const { responseCode } = await saveDataProduct(params)
    if (responseCode === 100000000) {
      message.success('保存成功')
      pageBack()
    }
  }

  // 下架
  const openModal = () => {
    visible.value = true
  }
  const cancelModal = () => {
    visible.value = false
    operationDesc.value = ''
  }
  const changeState = async () => {
    if (!operationDesc.value) {
      message.error('请输入下架原因')
      return
    }
    const params = {
      productId: id,
      targetStatus: 4,
      operationDesc: operationDesc.value,
    }
    const { responseCode } = await changeStatusDataProduct(params)
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('下架成功')
    }
    cancelModal()
    pageBack()
  }

  // 编辑数据产品
  const goAdd = () => {
    router.push({
      path: '/data-product/add',
      query: { id },
    })
  }

  /**回退页面*/
  const pageBack = () => {
    router.back()
  }

  // 获取操作记录
  const getActionRecord = async () => {
    const { responseCode, responseData } = await getDataProductActionRecord({ productId: id })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      actionRecordList.value = responseData.list
    }
  }

  // 获取审核记录
  const getAuditRecord = async () => {
    const { responseCode, responseData } = await getResourceApproveList({ resourceId: id })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      auditRecordList.value = responseData
    }
  }

  // 获取详情信息
  const getDataProductDetail = async () => {
    const { responseCode, responseData } = await getDataProductById({ dataProductId: id })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      dataProductDetail.value = responseData
      const list = responseData.customerDataRecordPageVOS
      initFileList(list)
    }
  }

  // 处理数据
  const initFileList = (list) => {
    list.map((item, index) => {
      const detail = JSON.parse(item.fileDetail)
      const isFileType = ['.csv', '.xls', '.xlsx'].includes(detail.fileName.substr(detail.fileName.lastIndexOf('.')).toLowerCase())
      if (isFileType) {
        structuredList.value.push(detail)
        structuredFileList.value.push({
          fileId: detail.fileId,
          fileName: detail.fileName,
        })
      } else {
        unstructuredList.value.push(detail)
      }
    })
    if (structuredList.value.length) {
      structuredPreviewFile(structuredList.value[0].fileId)
    }
  }

  onMounted(() => {
    if (id) {
      getDataProductDetail()
      getActionRecord()
      getAuditRecord()
    }
  })
</script>

<template>
  <div class="detail">
    <template v-if="dataProductDetail">
      <div class="detail-header">
        <div>{{ dataProductDetail.productName }}</div>
        <a-button type="primary" @click="pageBack">返回</a-button>
      </div>
      <div class="detail-info">
        <div class="detail-info-tag" v-if="dataProductDetail.dictResults && dataProductDetail.dictResults.values">
          <template v-if="dataProductDetail.dictResults.values.length">
            <a-tag color="green" v-for="item in dataProductDetail.dictResults.values" :key="item.code">{{ item.name ? item.name : '-' }}</a-tag>
          </template>
          <a-tag color="green">{{ dataProductDetail.downloadFlag === 1 && dataProductDetail.productSource === 2 ? '可下载' : '不可下载' }}</a-tag>
        </div>
        <a-row>
          <a-col :span="6">
            <text class="detail-info-label">创建用户：</text>
            <text>{{ dataProductDetail.userVO && dataProductDetail.userVO.userName ? dataProductDetail.userVO.userName : '-' }}</text>
          </a-col>
          <a-col :span="6">
            <text class="detail-info-label">所属平台：</text>
            <text>{{ dataProductDetail.productSource === 1 ? '个人' : '平台' }}</text>
          </a-col>
          <a-col :span="6">
            <text class="detail-info-label">创建时间：</text>
            <text>{{ formatDate(dataProductDetail.createdTime) }}</text>
          </a-col>
          <a-col :span="6">
            <text class="detail-info-label">申请时间：</text>
            <text>{{ formatDate(dataProductDetail.updatedTime) }}</text>
          </a-col>
        </a-row>
      </div>
      <div class="detail-info">
        <div class="detail-title">
          参与项目
          <!-- <text class="detail-title-count" v-if="dataProductDetail.productRequirePageVOS && dataProductDetail.productRequirePageVOS.length">
            {{ dataProductDetail.productBrief }}
          </text> -->
        </div>
        <!-- <template v-if="dataProductDetail.productRequirePageVOS && dataProductDetail.productRequirePageVOS.length">
          <a-row v-for="item in dataProductDetail.productRequirePageVOS" :key="item.requireId">
            <a-col :span="6">
              <text class="detail-info-label">{{ item.requireName }}</text>
            </a-col>
            <a-col :span="18">
              <text class="detail-info-label">创建时间：{{ item.requireTime ? formatDate(item.requireTime) : '-' }}</text>
            </a-col>
          </a-row>
        </template> -->
        <div class="detail-data-explain-list">{{ dataProductDetail.productBrief }}</div>
      </div>
      <div class="detail-info">
        <div class="detail-title">产品简介<a class="detail-title-count" @click="goDataDetail" v-if="structuredList.length">查看数据详情页</a></div>
        <div class="detail-data-list-box" v-if="structuredList.length">
          <div class="detail-data-title">{{ structuredList[0].fileName }}<text class="detail-data-title-count">预览行10</text></div>
          <div class="detail-data-list" v-if="listObj">
            <div class="detail-data-list-header" v-if="listObj.headers.length">{{ listObj.headers[0] }}</div>
            <div class="detail-data-list-body" v-if="listObj.data.length">
              <div class="detail-data-list-item" v-for="(item, index) in listObj.data" :key="index">
                <div class="detail-data-list-column ellipsis-line-1" v-for="subItem in item" :key="subItem" :title="subItem">{{ subItem }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="detail-data-explain-list">暂无</div>
        <div class="detail-data-explain">
          <div class="detail-data-title">详细描述</div>
          <div class="detail-data-explain-list">{{ dataProductDetail.productDetail || '暂无' }}</div>
        </div>
        <div class="detail-data-document">
          <div class="detail-data-title">文档</div>
          <div class="detail-data-document-list" v-if="unstructuredList.length">
            <div v-for="item in unstructuredList" :key="item.fileId">
              <template v-if="item.fileType !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'">
                <FileTextOutlined style="font-size: 30px" />
                <p>{{ item.fileName }}</p>
                <a-button type="link" size="small" @click="unstructuredPreviewFile(item.fileId)" :loading="previewLoading && fileId === item.fileId">预览</a-button>
              </template>
            </div>
          </div>
          <div v-else class="detail-data-explain-list">暂无</div>
        </div>
      </div>
      <div class="detail-info detail-info-display" v-if="dataProductDetail.pricingType">
        <div class="detail-title">价格</div>
        <div class="detail-info-price">{{ dataProductDetail.pricingType ? priceObj[dataProductDetail.pricingType] : '暂无' }}</div>
        <div class="detail-info-price">{{ dataProductDetail.priceAmount ? dataProductDetail.priceAmount : '' }}</div>
      </div>
      <div class="detail-info detail-info-display" v-if="dataProductDetail.status !== 2">
        <div class="detail-title">状态</div>
        <div class="detail-info-price">{{ statusObj[dataProductDetail.status] }}</div>
      </div>
      <div class="detail-info detail-info-display" v-if="dataProductDetail.status !== 2">
        <div class="detail-title">操作</div>
        <div class="detail-info-btn-box" v-if="dataProductDetail.status === 1">
          <a-button type="primary" @click="onSaveDataProduct">提交申请</a-button>
          <a-button class="detail-info-btn" type="primary" @click="goAdd">编辑</a-button>
          <a-button class="detail-info-btn" type="primary" v-if="dataProductDetail.downloadFlag === 1 && dataProductDetail.productSource === 2" @click="batchDownload">下载</a-button>
        </div>
        <div class="detail-info-btn-box" v-if="dataProductDetail.status === 3">
          <a-button type="primary" @click="openModal">下架</a-button>
          <a-button class="detail-info-btn" type="primary" v-if="dataProductDetail.downloadFlag === 1 && dataProductDetail.productSource === 2" @click="batchDownload">下载</a-button>
        </div>
        <div class="detail-info-btn-box" v-if="dataProductDetail.status === 4">
          <a-button type="primary" @click="goAdd">编辑</a-button>
          <a-button class="detail-info-btn" type="primary" v-if="dataProductDetail.downloadFlag === 1 && dataProductDetail.productSource === 2" @click="batchDownload">下载</a-button>
        </div>
      </div>
      <div class="detail-info" v-if="dataProductDetail.status !== 2 && actionRecordList.length">
        <div class="detail-title">操作记录</div>
        <div class="detail-info-record-box">
          <div class="detail-info-record" v-for="item in actionRecordList" :key="item.id">
            <div><text class="detail-info-label">操作人：</text>{{ item.operatorName }}</div>
            <div><text class="detail-info-label">操作时间：</text>{{ formatDate(item.operationTime) }}</div>
            <div><text class="detail-info-label">操作说明：</text>{{ item.operationDesc }}</div>
          </div>
        </div>
      </div>
      <div class="detail-info" v-if="dataProductDetail.status === 2">
        <div class="detail-info-audit-tab">
          <div :class="actionTab === 1 ? 'detail-info-audit-tab-item active-tab-item' : 'detail-info-audit-tab-item'" @click="actionTab = 1">审核</div>
          <div :class="actionTab === 2 ? 'detail-info-audit-tab-item active-tab-item' : 'detail-info-audit-tab-item'" @click="actionTab = 2">审核记录</div>
        </div>
        <div class="detail-info-audit-box" v-if="actionTab === 1">
          <a-radio-group v-model:value="auditValue">
            <a-radio :value="3">通过</a-radio>
            <a-radio :value="4">不通过</a-radio>
          </a-radio-group>
          <div class="detail-info-audit-idea"
            >654321@@@
            <text>审核意见</text>
            <a-textarea v-model:value="auditIdea" style="width: 400px" :maxlength="200" placeholder="请输入" />
          </div>
          <div class="detail-info-audit-idea">
            <a-button type="primary" @click="approveRequire">提交</a-button>
          </div>
        </div>
        <div class="detail-info-record-box" v-if="actionTab === 2">
          <template v-if="auditRecordList.length">
            <div class="detail-info-record" v-for="item in auditRecordList" :key="item.id">
              <div><text class="detail-info-label">审核结果：</text>{{ item.approveStatus === 3 ? '通过' : item.approveStatus === 4 ? '不通过' : '' }}</div>
              <div><text class="detail-info-label">审核人：</text>{{ item.approveBy }}</div>
              <div><text class="detail-info-label">审核时间：</text>{{ formatDate(item.approveTime) }}</div>
              <div><text class="detail-info-label">审核意见：</text>{{ item.approveMsg }}</div>
            </div>
          </template>
          <div class="detail-info-record" v-else>暂无</div>
        </div>
      </div>
    </template>
    <!-- 预览图片 -->
    <a-modal v-model:visible="previewVisible" title="预览" :footer="null" @cancel="handleCancel">
      <img alt="" style="width: 100%" :src="previewImage" />
    </a-modal>
    <!-- 下架 -->
    <a-modal v-model:visible="visible" title="下架" @cancel="cancelModal" @ok="changeState">
      <p>下架原因：</p>
      <a-textarea v-model:value="operationDesc" placeholder="请输入" />
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
  .detail {
    width: 100%;
    padding: 0 24px 30px;
    background: #fff;
    border-radius: 2px;

    .detail-header {
      width: 100%;
      height: 64px;
      margin-bottom: 20px;
      border-bottom: 1px solid #e2e3e5;
      font-size: 16px;
      font-weight: bold;
      color: #000;
      line-height: 64px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .detail-info {
      width: 100%;
      padding-bottom: 20px;
      margin-bottom: 20px;
      border-bottom: 1px solid #e2e3e5;
      font-size: 13px;

      &:last-child {
        border: none;
      }

      .detail-info-tag {
        margin-bottom: 10px;
      }

      .detail-info-label {
        color: #000;
      }

      .detail-title {
        color: #000;
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 20px;

        .detail-title-count {
          padding-left: 40px;
        }
      }

      .detail-data-info {
        width: 450px;
        display: flex;
        border-top: 1px solid #e2e3e5;
        border-bottom: 1px solid #e2e3e5;
        border-right: 1px solid #e2e3e5;
        margin-bottom: 20px;

        .detail-data-item {
          width: 150px;
          padding-top: 10px;
          border-left: 1px solid #e2e3e5;
          text-align: center;
        }
      }

      .detail-data-title {
        color: #000;
        font-weight: 600;
        margin-bottom: 10px;

        .detail-data-title-count {
          padding-left: 100px;
          font-weight: 400;
        }
      }

      .detail-data-explain-list {
        width: 450px;
        border: 1px solid #e2e3e5;
        border-radius: 12px;
        padding: 10px;
        color: #000;
        margin-bottom: 20px;

        div {
          margin-bottom: 20px;
        }
      }

      .detail-data-document-list {
        width: 100%;
        display: flex;
        align-items: center;
        text-align: center;

        div {
          margin-right: 20px;

          p {
            margin: 5px 0;
            color: #000;
          }
        }
      }

      .detail-info-btn-box {
        margin-left: 100px;
        box-sizing: border-box;

        .detail-info-btn {
          margin-left: 20px;
        }
      }

      .detail-info-record-box {
        width: 100%;
        box-sizing: border-box;

        .detail-info-record {
          border: 1px solid #e2e3e5;
          padding: 10px 20px;
          margin-bottom: 20px;
          border-radius: 12px;
        }
      }

      .detail-data-list-box {
        width: 100%;
        border: 1px solid #e2e3e5;

        .detail-data-title {
          border-bottom: 1px solid #e2e3e5;
          padding: 10px;
        }

        .detail-data-list {
          max-width: calc(100% - 30px);
          width: max-content;
          margin: 15px;
          border-top: 1px solid #e2e3e5;
          border-left: 1px solid #e2e3e5;
          overflow: hidden;
          overflow-x: scroll;

          .detail-data-list-header {
            padding: 0 5px;
            line-height: 30px;
            text-align: center;
            color: #000;
            border-right: 1px solid #e2e3e5;
            border-bottom: 1px solid #e2e3e5;
          }

          .detail-data-list-item {
            display: flex;
            height: 30px;
          }

          .detail-data-list-column {
            width: 100px;
            padding: 0 5px;
            line-height: 30px;
            text-align: center;
            color: #000;
            border-right: 1px solid #e2e3e5;
            border-bottom: 1px solid #e2e3e5;
          }
        }
      }

      .detail-info-audit-tab {
        width: 100%;
        margin-bottom: 20px;
        display: flex;

        .detail-info-audit-tab-item {
          color: #000;
          font-size: 16px;
          font-weight: 600;
          margin-right: 30px;
          cursor: pointer;
        }

        .active-tab-item {
          color: #08979c;
        }
      }

      .detail-info-audit-box {
        width: 100%;

        .detail-info-audit-idea {
          display: flex;
          margin-top: 20px;

          text {
            padding-right: 20px;
          }
        }
      }
    }

    .detail-info-display {
      display: flex;
      align-items: center;

      .detail-info-price {
        padding-left: 100px;
        color: #000;
      }

      .detail-title {
        margin: 0;
      }
    }
  }
</style>
